const e = require("express");
const express = require("express");
const db = require("./../lib/db");

const router = express.Router(); // 使用express路由

// 查询对应用户的所有购物车数据
router.get("/all", (req, res) => {
    // ?uid=1
    const uid = req.query.uid;
    if (!uid) {
        res.send({ code: 1, message: "用户编号不允许空" });
        return;
    }
    const sql = `SELECT * FROM carts c,goods g 
    where c.goods_id = g.id 
    and c.user_id = ?`;
    db.query(sql, uid)
        .then((ret) => {
            res.send({ code: 0, data: ret });
        })
        .catch((err) =>
            res.send({ code: 2, message: "查询购物车数据失败:" + e.message })
        );
});
// 添加商品到购物车
router.all("/update", (req, res) => {
    // 获取商品编号及用户编号
    const uid = req.query.uid,
        gid = req.query.gid,
        act = req.query.act; // 操作 add:表示增加 other:表示减少
    // 判断参数是否正确
    if (!uid || !gid || !act) {
        res.send({ code: 1, message: "请求的参数不正确" });
        return;
    }
    // 查询购物车中是否已经存在对应的商品
    db.queryOne("select * from carts where goods_id=? and user_id=?", gid, uid)
        .then((data) => {
            // 查询最新的价格
            db.queryOne("select price from goods where id = ?", gid).then((g) => {
                let sql = "",
                    count = 0;
                // important 注意参数的顺序要一致
                if (data) {
                    // 表示购物车里已经存在对应的商品
                    sql =
                        "update carts set add_price=?,count=? where goods_id=? and user_id=?";
                    // 判断时 增加还是减少
                    if (act == "add") {
                        count = data["count"] + 1; // 现有数据 + 1
                    } else {
                        count = data["count"] - 1; // 现有数据 - 1
                    }
                } else {
                    count = 1;
                    sql =
                        "insert into carts (add_price,count,goods_id,user_id) values (?,?,?,?)";
                }
                db.execute(sql, g.price, count, gid, uid).then((ret) => {
                    res.send({ code: 0, message: "更新购物车成功" });
                });
            });
        })
        .catch((err) => res.send({ code: 2, message: "更新购物车失败" }));
});
function fillAnyZero(v,length){
    const len = length - v.toString().length;
    return Array(len).fill('0').join('') + v;
}
function fillZero(v){
    return v < 10 ? '0' + v:v;
}
function getOrderId(){
    const now = new Date();
    const y = now.getFullYear(),
        mon = now.getMonth() + 1,
        d = now.getDate(),
        h = now.getHours(),
        m = now.getMinutes(),
        s = now.getSeconds();
        return y + fillZero(mon) + fillZero(d)+ fillZero(h)+ fillZero(m)+ fillZero(s);
}
// 由于操作可能比较多 所以使用同步
router.post('/submit',async (req,res)=>{
    const from = req.query.from; // 来源 
    const uid = req.query.uid; // 用户id
    const totalPrice = req.query.price; // TODO 总金额 实际应该后端实时计算
    const goods = req.body; // 商品数据
    try{
        const order_id = getOrderId(); // 创建订单编号
        // 创建订单
        const sql_order = 'insert into orders (id,uid,price) values (?,?,?)';
        await db.execute(sql_order,order_id,uid,totalPrice); 
        // 创建订单商品 - 四个列都要填写数据
        const sql_order_goods = 'insert into order_goods values (?,?,?,?)';
        let ids = '0'
        // 循环将商品添加到数据表
        for(let g of goods){
           await db.execute(sql_order_goods,order_id,g.id,0,g.count);
           ids += ','+g.id;
        }
        // 根据来源 删除购物车数据
        db.execute(`delete from carts where user_id=? and goods_id in (${ids})`,uid)
        res.send({code:0})
    }catch(e){
        res.send({code:1,message:'创建订单失败'});
    }
})

module.exports = router; // 暴露路由
